﻿using System.Collections.Generic;
using System.Linq;
using CID.Domain.Development;
using QuickGraph;
using QuickGraph.Algorithms;

namespace CID.Execution.Controller.Support
{
    sealed class ComponentDependencyResolver
    {
        private AdjacencyGraph<IComponent, Edge<IComponent>> CreateDependencyGraph(IEnumerable<IVersion> affectedVersions)
        {
            var result = new AdjacencyGraph<IComponent, Edge<IComponent>>();
            result.AddVertexRange(affectedVersions.Select(x => x.Component));
            foreach (var version in affectedVersions)
                foreach (var dependency in version.DependsOn)
                    if(result.ContainsVertex(dependency)) result.AddEdge(new Edge<IComponent>(version.Component, dependency));

            return result;
        }

        private IEnumerable<IComponent> dependencyGraphTopologicallySorted;
        public ComponentDependencyResolver(IEnumerable<IVersion> affectedVersions)
        {
            var dependencyGraph = CreateDependencyGraph(affectedVersions);
            
            dependencyGraphTopologicallySorted = dependencyGraph.TopologicalSort();

            dependencyGraph.Clear();
        }

        public IEnumerable<IComponent> GetActivationSequence()
        {
            return dependencyGraphTopologicallySorted.Reverse();
        }

        public IEnumerable<IComponent> GetDeactivationSequence()
        {
            return dependencyGraphTopologicallySorted;
        }
    }
}
